"""
Function to import and analyze iTOMs dielectric tomography data
Created: Brent Maranzano
Last Modified: May 27, 2014
"""

import csv
from matplotlib import pyplot as plt
import numpy as np
from numpy.lib.recfunctions import append_fields
from figures.matplotlib.defaults import Defaults as FigDefaults
from pdb import set_trace

def import_cond_tomogram(fname):
    """
    Import the conductivity tomogram from and exported
    run in csv format. The pixel information was determined
    by compaing the exported csv file with the tomogram graph
    in the iTOMs software. Pixel 1 is the upper-left (vessel top-center).
    Last pixel (200) is the bottom-right (vessel bottom-outside).
    fname : text file from iTOMs instrument of the conductivity tomogram
    return : numpy structured array
    Created: Brent Maranzano
    Last Modified: May 27, 2014
    """
    with open(fname, mode='r') as fObj:
        csv_r = csv.reader(fObj)
        _, _, frames, filename = csv_r.next()
        _, _, pixels = csv_r.next()
        frames = int(frames.strip().split(' ')[0])
        pixels = int(pixels.strip().split(' ')[0])
        data = np.zeros((frames), dtype={'names':['t', 'f', 'c'], 
            'formats':['|S10', np.int32, '(20,10)float'],
            'titles':['time', 'frame', 'conductivity']})
        for i, row in enumerate(csv_r):
            data['t'][i] = row[0]
            data['f'][i] = int(row[1])
            for y in xrange(20):
                for x in xrange(10):
                    data['c'][i,y,x] = row[2+y*10+x]
    return data

class iToms(FigDefaults):
    """
    class to analyze itoms data in the csv file
    """
    def __init__(self):
        FigDefaults.__init__(self)

    def import_data(self,fname):
        """
        Reads in the 17 columns of the csv file used
        to store the voltage.
        fname - string of the csv file name
        returns numpy array [points,17] where points 
        are the number of time points
        """
        data = []
        f = open(fname)
        csv_read = csv.reader(f)
        for r in csv_read:
            data.append(r)
        f.close()
        data = np.array(data)
        voltage = np.array(data[:,1:17],'f8')
        return voltage

    def plot_data(self,voltage,delta_t):
        """
        Plots the voltage of three electrodes 
        (columns 0,9 and 15 in the csv file)
        as a function of time.
        voltage - numpy array of voltages produced from the import_data method
        delta_t - float time between scans in seconds
        return nothing
        """
        time_axis = np.arange(0,delta_t*voltage.shape[0],delta_t)
        plt.ion()
        self.set_defaults(columns=2,subplots=1)       
        fig = plt.figure()
        ax = fig.add_subplot(111)
        columns = [2,11,17]
        for i in range(3):
            ax.plot(time_axis/60.,voltage[:,i],label='column %i'%(columns[i]),color=self.linecolors[i],ls=self.linestyles[i])
        ax.set_xlabel('time (min)')
        ax.set_ylabel('voltage (mV)')
        ax.set_xlim(0,30)
        ax.legend(loc=4)
        plt.draw()
        plt.show()
        return [fig,ax]
